package tech.daoxuan.web.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * 在这里可以注入 操作数据库的接口，查询用户信息
 *  UserDetails 封装了用户信息
 *
 *  注意 获取用户信息 在这里写就OK了
 *  只需要实现UserDetailService 就行  在配置文件中配置 登陆方式，和登陆页面即可
 *
 *
 *  账户的加密解密
 *     需要在容器中 添加 加密解密的对象
 *
 */
@Component
public class MyUserDetailService implements UserDetailsService , SocialUserDetailsService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       logger.info("表单登陆用户输入的用户名："+username);
//        //根据查找到的用户， 判断登陆用户的 账号状态
//        String encode = passwordEncoder.encode("123456");
//        logger.info("数据库密码-----"+encode);
        //return new User(username, encode,true,true,true,true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return BuilderUser(username);
    }


    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        logger.info("社交登陆用户的用户ID："+userId);
        return BuilderUser(userId);
    }

    private SocialUserDetails BuilderUser(String userId) {

        //根据查找到的用户， 判断登陆用户的 账号状态
        String encode = passwordEncoder.encode("123456");
        logger.info("数据库密码-----"+encode);
        return new SocialUser(userId, encode,true,true,true,true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
